import java.util.PriorityQueue;

public class Solution230 {

    PriorityQueue<Integer> queue=new PriorityQueue<>((a,b)->b-a);

    public static class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }
    public int kthSmallest(TreeNode root, int k) {
        search(root,k);
        return queue.peek();
    }
    public void search(TreeNode root,int k){
        if (queue.size()<k){
            queue.offer(root.val);
        }else if (root.val<queue.peek()){
            queue.poll();
            queue.offer(root.val);
        }
        if (root.left!=null){
            search(root.left,k);
        }
        if (root.right!=null){
            search(root.right,k);
        }
    }

    public static void main(String[] args) {
        TreeNode node3=new TreeNode(3,new TreeNode(1,null,new TreeNode(2,null,null)),new TreeNode(4,null,null));
        System.out.println(new Solution230().kthSmallest(node3,2));
    }
}
